package com.archive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.archive.common.TokenGenerator;
import com.archive.entity.SysExpire;
import com.archive.mapper.SysExpireMapper;
import com.archive.service.SysExpireService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * token过期表 服务实现类
 * </p>
 *
 * @author Janus
 * @since 2023-10-04
 */
@Service
public class SysExpireServiceImpl extends ServiceImpl<SysExpireMapper, SysExpire> implements SysExpireService {


    @Override
    public void logout(Long userId) {
        /*根据userId查询token存储信息*/
        SysExpire expiresEntity=getByUserId(userId);
        if(expiresEntity!=null){
            expiresEntity.setToken(TokenGenerator.generateValue());
            this.updateById(expiresEntity);
        }
    }

    @Override
    public SysExpire saveToken(Long userId) {
        /*生成token值*/
        String token= TokenGenerator.generateValue();
        /*生成有效期*/
        LocalDateTime localDateTime = LocalDateTime.now().plusHours(12);
        /*根据用户编号获取当前token存储情况*/
        SysExpire sysExpire=getByUserId(userId);
        /*判断是否存着token信息*/
        if(sysExpire==null){
            /*实例化对象*/
            sysExpire=new SysExpire();
            /*存入信息*/
            sysExpire.setUserId(userId);
            sysExpire.setToken(token);
            sysExpire.setExpires(localDateTime);
            /*保存token信息*/
            this.save(sysExpire);
        }else{
            /*更新token和有效期*/
            sysExpire.setExpires(localDateTime);
            sysExpire.setToken(token);
            this.updateById(sysExpire);
        }
        return sysExpire;
    }
    private SysExpire getByUserId(long userId){
        return this.getOne(new QueryWrapper<SysExpire>().eq("user_id",userId));
    }
}
